package com.quanyan.assets.service.impl;

import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.api.enums.Currency;
import com.quanyan.assets.emun.AssetsErrorEnum;
import com.quanyan.assets.entity.TbCurrency;
import com.quanyan.assets.entity.TbCurrencyExample;
import com.quanyan.assets.mapper.ETbCurrencyMapper;
import com.quanyan.assets.mapper.TbCurrencyMapper;
import com.quanyan.assets.request.ReqCurrency;
import com.quanyan.assets.service.CurrencyService;
import com.quanyan.common.annotation.ServiceExceptionHandler;
import com.quanyan.common.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by wmb on 2016/6/6.
 */
@Service("currencyService")
public class CurrencyServiceImpl implements CurrencyService{
    @Autowired
    private ETbCurrencyMapper etbCurrencyMapper;
    @Autowired
    private TbCurrencyMapper tbCurrencyMapper;
    @Override
    public APIResponse<BigDecimal> exchangeRatioByName(String currencyName) {
        if(null==currencyName){
            throw new BizException(AssetsErrorEnum.CURRENCY_NAME_NULL);
        }
        //获取资产ID
        Byte id= Currency.getIdByName(currencyName);
        if(null==id){
            throw new BizException(AssetsErrorEnum.CURRENCY_NAME_NOT_EXISTS);
        }
        //获取兑换比例
        return exchangeRatioByAssetsId(id);
    }

    @Override
    public APIResponse<BigDecimal> exchangeRatioById(Byte id) {
        if(null==id){
            throw new BizException(AssetsErrorEnum.ASSETS_ID_NULL);
        }
        //获取兑换比例

        return exchangeRatioByAssetsId(id);
    }

    @Override
    @Valid
    public APIResponse update(APIRequest<ReqCurrency> apiRequest) {
        ReqCurrency reqCurrency=apiRequest.getData();
        if(null==reqCurrency.getAssetsId()){
            throw new BizException(AssetsErrorEnum.ASSETS_ID_NULL);
        }
        if(null==reqCurrency.getRmbAmount()){
            throw new BizException(AssetsErrorEnum.RMB_AMOUNT_NULL);
        }
        etbCurrencyMapper.updateAmonutByAssetsId(reqCurrency.getAssetsId(),reqCurrency.getRmbAmount());
        return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
    }


    private APIResponse<BigDecimal> exchangeRatioByAssetsId(Byte id) {
        //获取货币
        TbCurrencyExample tbCurrencyExample=new TbCurrencyExample();
        tbCurrencyExample.createCriteria().andAssetsIdEqualTo(id);
        List<TbCurrency> currencyList=tbCurrencyMapper.selectByExample(tbCurrencyExample);
        if(currencyList.isEmpty()){
            throw new BizException(AssetsErrorEnum.CURRENCY_RECORD_DO_NOT_EXISTS);
        }
        //获取兑换比例
        return APIResponse.returnSuccess(new BigDecimal(1).divide(new BigDecimal(currencyList.get(0).getRmbAmount())));
    }
}
